package com.ifnk.portaljava.dapWeb.hlyt.servlet;
/**
 * <p>Title: 导出二进制类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author WenSheng.Song.hlyt@gmail.com
 * @version 1.0
 */

import com.ifnk.portaljava.dapWeb.socket.Client;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Locale;
import java.util.ResourceBundle;

@SuppressWarnings("serial")
public class CDRExport extends HttpServlet {
	public static Log loger = LogFactory.getLog(CDRExport.class);
	public static String directory;
	static {
		Locale locale = Locale.ENGLISH;
		ResourceBundle localResource = ResourceBundle.getBundle("Socket",
				locale);
		directory = localResource.getString("pcapNativeFile");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String sessionId = request.getParameter("sessionId");
		String key = request.getParameter("key");
		
		String fileName = "cdr.dat"; 

		response.setContentType("text/plain"); 
		response.setHeader("Dontent-disposition", "attachment;filename=" + fileName); 

		OutputStream out = null;
		InputStream in = null;
		out = response.getOutputStream();
		sessionId = ((Client)request.getSession().getAttribute("client")).getCp().getRequestDateFromProxyId();
		File file = new File(directory + File.separator + sessionId
				+ File.separator + key);
		try {
			Thread.sleep(3000);
			readDataFromFile(file, in, out);
		}catch(Exception e) {
			loger.error("WebServer Exception " + e.toString());
		}
		if (in != null)
			in.close();
		if (out != null)
			out.close();
	}
	
	public void readDataFromFile(File file, InputStream in, OutputStream out) throws IOException {
		if (file.exists()) {
			File[] fileList = file.listFiles();
//			Util.fileSort(fileList);
			for (int i=0; i<fileList.length; i++) {
				in = new FileInputStream(fileList[i]);
				byte[] data = new byte[(int) fileList[i].length()];
				in.read(data);
				out.write(data);
				out.flush();
			}
		}
	}
	
}
